package com.chiaching.webmagic.handler;

import com.chiaching.framwork.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.Html;

import javax.annotation.PostConstruct;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 京东商品详情页  https://item.jd.com/xxxxxxx.html
 * @author jiajing.he
 * @date 2021/7/29 上午10:07
 */
@Slf4j
//@Component
public class JDGoodsProcessor implements PageProcessor {


    private static AtomicLong number = new AtomicLong(1000800000);

    /**
     * 部分一：抓取网站的相关配置，包括编码、抓取间隔、重试次数等
     */
    private Site site = Site.me()
            //重试次数
            .setRetryTimes(3)
            //超时时间
            .setTimeOut(3000)
            //抓取间隔
            .setSleepTime(50)
            //设置编码
            .setCharset("utf-8")
            //域名
            //.setDomain("jd.com")
            .setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:73.0) Gecko/20100101 Firefox/73.0");
            //.addHeader()
            //设置cookie
            //.addCookie()

    @Override
    public void process(Page page) {
        //page.getHtml().links().regex("https://item.jd.com/\\d{8,12}.html").all();
        try {
            page.addTargetRequest(createNextUrl());
            Html html = page.getHtml();
            //商品名
            String name = html.$(".itemInfo-wrap .sku-name", "text").toString();
            if (StringUtils.isEmpty(name)){
                return;
            }
            page.putField("skuName",name );
            //商品价格 是渲染的 需要发现ajax请求地址 todo
            page.putField("price", html.$(".itemInfo-wrap .dd span").toString());
            //商品品牌
            page.putField("brand", html.$(".p-parameter ul li","title").toString());
            //商品属性
            page.putField("field", html.$(".p-parameter .parameter2.p-parameter-list").toString());
            log.info("{}",page.getResultItems());
        } catch (Exception e) {
            log.error("error ... [{}]", e);
        }
    }

    private String createNextUrl(){
        return  "https://item.jd.com/" + number.incrementAndGet() + ".html";
    }

    @Override
    public Site getSite() {
        return this.site;
    }

    @PostConstruct
    public void start(){
        Spider.create(new JDGoodsProcessor())
                //从"https://github.com/code4craft"开始抓
                .addUrl("https://item.jd.com/100019677418.html")
                //开启5个线程抓取
                .thread(5)
                //启动爬虫
                .run();
    }

    public static void main(String[] args) {
            /*String str = "https://item.jd.com/100019677418.html";
            String pattern = "https://item.jd.com/\\d{8,12}.html";

            Pattern r = Pattern.compile(pattern);
            Matcher m = r.matcher(str);
            System.out.println(m.matches());*/



        //System.out.println(HttpUtil.createPost("https://item.jd.com/100019677418.html").execute().body());
    }

}
